﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace HttpFileServer
{
    public class DirListResponse : FemtoHttpd.SimpleResponse
    {
        public static DiskLruCache lruCache = new DiskLruCache("cache",
            (string key, out string data) =>
            {
                var path = key.Substring(0, key.IndexOf('?'));
                data = Util.GetThumbnail(path);
                return true;
            });
        private DirListResponse(Stream output) : base(output)
        {
            ContentType = "text/html";
        }
        private static int TryGetStart(Dictionary<string, string> p)
        {
            return p.TryGetValue("start", out var start) && int.TryParse(start, out var result) ? result : 0;
        }
        public static DirListResponse Create(Stream output, string dirName, string basePath, Dictionary<string, string> parameters)
        {
            var di = new DirectoryInfo(dirName);
            if (!di.Exists) return null;
            var dlr = new DirListResponse(output);
            string firstHtml = "<html>\n" + "<head>\n" +
                "<meta charset=\"UTF-8\"/>" +
                "<meta name =\"viewport\" content =\"width=device-width, initial-scale=1\" />" +
                "<style>\n" +
                "body{text-align: center;}" +
                //"img{ width=500px;}" +
                "div.imgcard{" +
                //"padding: 10px;"+
                "margin-left:auto;" +
                "margin-right:auto;" +
                "width:300px;" +
                "height:auto;" +
                "box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" +
                //"text-align: center;" +
                "}" +
                "div.container{padding: 10px;}" +
                "</style></head>\n" +
                "<body><a href=\"..\">上一级目录</a><br/><br/>";
            string endHtml = "</body></html>";

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(firstHtml);

            var dis = di.GetDirectories();
            var fis = di.GetFiles();

            int start = TryGetStart(parameters);
            int end = start + 50;
            int index = 0;
            int current = start / 50 + 1;
            int total = (dis.Length + fis.Length + 49) / 50;
            Trace.WriteLine($"start:{start}/{total}");
            if (start >= 50)
            {
                sb.AppendLine($"<a href=\"?start={start - 50}\">上一页</a>&nbsp;&nbsp;&nbsp;&nbsp;\n");
            }
            sb.AppendLine($"{current}/{total}&nbsp;&nbsp;<a href=\"?start={end}\">下一页</a><br><br>\n");
            
            foreach (var subDi in dis)
            {
                if (index >= start && index < end)
                    sb.AppendLine(ItemDir(subDi.Name, subDi.Name));
                index++;
            }
            foreach (var subFi in fis)
            {
                if (index >= start && index < end)
                    sb.AppendLine(ItemFile(subFi.Name, subFi.Name, lruCache.Get(subFi.FullName + "?" + subFi.LastWriteTime.Ticks, out var data) ? data : "", basePath));
                index++;
            }

            if (start >= 50)
            {
                sb.AppendLine($"<a href=\"?start={start - 50}\">上一页</a>&nbsp;&nbsp;&nbsp;&nbsp;\n");
            }
            sb.AppendLine($"{current}/{total}&nbsp;&nbsp;<a href=\"?start={end}\">下一页</a><br><br>\n");

            sb.AppendLine(endHtml);
            dlr.Body = sb.ToString();
            return dlr;
        }
        private static string ItemDir(string name, string path)
        {
            return $"<a href=\"{HttpUtility.UrlEncode(path, Encoding.UTF8)}/\">{name}</a><br><br>\n";
        }
        private static string ItemFile(string name, string path, string imagedata, string basePath)
        {
            return "<div class=\"imgcard\">" +
                    $"<br/><a href=\"{HttpUtility.UrlEncode(path, Encoding.UTF8)}\"><img src=\"{imagedata}\"/></a><br/><br/>{name}&nbsp;&nbsp;<a href=\"x://fhs.null/?uri={HttpUtility.UrlEncode(basePath + path, Encoding.UTF8)}\">&nbsp;X&nbsp;</a><br><br/>\n" +
                     "</div><br/>\n";
        }
    }
}
